package com.example.config;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClientFactory;
import com.mongodb.client.MongoClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoClientFactoryBean;
import org.springframework.data.mongodb.core.MongoTemplate;

/**
 * MongoDB配置
 *
 * @author linfeng
 * @date 2021/10/19
 */
@Configuration
public class MongoConfig {

    private static final String DATABASE_NAME = "mongodb_study";

    /**
     * 注册Mongo实例的第一种方法：直接创建MongoClient并将其声明为bean
     * @return
     */
    @Bean
    public MongoClient mongoClient(){
        return MongoClients.create("mongodb://localhost:27017/");
    }

    /**
     * 注册Mongo实例的第二种方法：使用MongoClientFactoryBean
     * @return
     */
    /*
    @Bean
    public MongoClientFactoryBean mongoClientFactoryBean(){
        MongoClientFactoryBean factoryBean = new MongoClientFactoryBean();
        factoryBean.setHost("localhost");
        return factoryBean;
    }*/

    @Bean
    public MongoTemplate mongoTemplate(MongoClient mongoClient){
        return new MongoTemplate(mongoClient,DATABASE_NAME);
    }
}
